# encoding=utf-8
# author:梁子龙
from typing import Generic, List

from fastapi.encoders import jsonable_encoder
from sqlalchemy import select
from sqlalchemy.orm import Session

from api.schemas import ModelType, CreateSchema, UpdateSchema


class BaseDAO(Generic[ModelType, CreateSchema, UpdateSchema]):
    """

    """
    model: ModelType  # 数据库模型类
    """增删改查"""

    def get(self, session: Session, offset=0, limit=10) -> List[ModelType]:
        """

        :param session:
        :param offset:
        :param limit:
        :return:
        """
        return session.scalars(select(self.model).offset(offset).limit(limit)).all()

    def get_by_id(self, session: Session, pk: int) -> ModelType:
        """

        :param session:
        :param pk:
        :return:
        """
        return session.get(self.model, pk)

    def create(self, session: Session, obj_in: CreateSchema) -> ModelType:
        """

        :param session:
        :param obj_in:
        :return:
        """
        obj = self.model(**jsonable_encoder(obj_in))  # pydantic模型类转化为字典
        session.add(obj)
        session.commit()

    def update(self, session: Session, pk: int, obj_in: UpdateSchema) -> ModelType:
        """

        :param session:
        :param pk:
        :param obj_in:
        :return:
        """
        obj = self.get_by_id(session, pk)
        update_data = obj_in.dict(exclude_unset=True)
        for key, val in update_data.items():
            setattr(obj, key, val)

    def count(self,session:Session):

        return  session.query(self.model).count()

